import React, { useState, useEffect } from 'react';
import { Link, useLocation, useHistory } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { creditsService, UserCredits } from '../services/credits';
import UserDropdown from './UserDropdown';

const Navbar: React.FC = () => {
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);
  const [userCredits, setUserCredits] = useState<UserCredits | null>(null);
  
  const { user, isAuthenticated, logout: authLogout } = useAuth();
  const location = useLocation();
  const history = useHistory();


  useEffect(() => {
    // 从后端获取用户积分信息
    const loadUserCredits = async () => {
      if (isAuthenticated && user) {
        try {
          const credits = await creditsService.getUserCredits(user.id);
          setUserCredits(credits);
        } catch (error) {
          console.error('Failed to load credits:', error);
          setUserCredits(null);
        }
      } else {
        setUserCredits(null);
      }
    };

    loadUserCredits();
  }, [isAuthenticated, user, location]);

  // 添加点击外部关闭菜单的功能
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (isUserMenuOpen && !target.closest('.user-menu-container')) {
        setIsUserMenuOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isUserMenuOpen]);



  const isActive = (path: string) => {
    return location.pathname === path;
  };

  const handleLogout = async () => {
    try {
      await authLogout();
      setIsUserMenuOpen(false);
      setUserCredits(null);
      history.push('/');
    } catch (error) {
      console.error('登出失败:', error);
      // 即使失败也跳转到首页
      history.push('/');
    }
  };

  // 获取用户显示名称
  const getUserDisplayName = () => {
    if (user?.firstName && user?.lastName) {
      return `${user.firstName} ${user.lastName}`;
    }
    if (user?.firstName) {
      return user.firstName;
    }
    if (user?.email) {
      return user.email.split('@')[0];
    }
    return 'User';
  };

  // 获取用户头像字母
  const getUserAvatarLetter = () => {
    const displayName = getUserDisplayName();
    return displayName.charAt(0).toUpperCase();
  };

  return (
    <nav className="bg-gray-900 text-white shadow-lg">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16">
          {/* Mobile menu button - moved to left */}
          <div className="md:hidden">
            <button
              onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
              className="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-white hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white"
            >
              <span className="sr-only">Open main menu</span>
              {/* Hamburger icon */}
              <svg
                className="h-6 w-6"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d={isMobileMenuOpen ? "M6 18L18 6M6 6l12 12" : "M4 6h16M4 12h16M4 18h16"}
                />
              </svg>
            </button>
          </div>

          {/* Logo - centered on mobile */}
          <div className="flex-shrink-0 md:flex-shrink-0 flex items-center">
            <img src="/logo192.png" alt="logo" className="w-10 h-10 mr-2 animate-spin-slow" />
            <Link to="/" className="text-xl font-bold">
              RoomGPT
            </Link>
          </div>

          {/* 用户头像 - 在移动端也显示 */}
          <div className="md:hidden">
            {isAuthenticated ? (
              <div 
                className="relative user-menu-container"
                onClick={() => setIsUserMenuOpen(!isUserMenuOpen)}
              >
                {user?.picture ? (
                  <img
                    src={user.picture}
                    alt="User Avatar"
                    className="w-8 h-8 rounded-full object-cover"
                  />
                ) : (
                  <div className="w-8 h-8 rounded-full bg-blue-500 flex items-center justify-center text-white">
                    {getUserAvatarLetter()}
                  </div>
                )}
                
                {isUserMenuOpen && (
                  <div 
                    className="absolute right-0 z-[999] user-menu-container"
                    style={{ top: '100%', marginTop: '8px' }}
                  >
                    <UserDropdown />
                  </div>
                )}
              </div>
            ) : (
              <Link
                to="/login"
                className="px-3 py-2 rounded-md text-sm font-medium text-gray-300 hover:text-white hover:bg-gray-700"
              >
                Login
              </Link>
            )}
          </div>

          {/* Desktop Navigation */}
          <div className="hidden md:block">
            <div className="ml-10 flex items-center space-x-4">
              {/* 普通页面导航 */}
              <div className="hidden md:flex space-x-8">
                <Link 
                  to="/" 
                  className={`px-3 py-2 rounded-md text-sm font-medium ${
                    isActive('/') 
                      ? 'bg-gray-800 text-white' 
                      : 'text-white hover:text-white hover:bg-gray-700'
                  }`}
                >
                  Home
                </Link>
                <Link 
                  to="/styles" 
                  className={`px-3 py-2 rounded-md text-sm font-medium ${
                    isActive('/styles') 
                      ? 'bg-gray-800 text-white' 
                      : 'text-white hover:text-white hover:bg-gray-700'
                  }`}
                >
                  Styles
                </Link>
                <Link 
                  to="/gallery" 
                  className={`px-3 py-2 rounded-md text-sm font-medium ${
                    isActive('/gallery') 
                      ? 'bg-gray-800 text-white' 
                      : 'text-white hover:text-white hover:bg-gray-700'
                  }`}
                >
                  Gallery
                </Link>
                {/* <Link 
                  to="/room-design" 
                  className={`px-3 py-2 rounded-md text-sm font-medium ${
                    isActive('/room-design') 
                      ? 'bg-gray-800 text-white' 
                      : 'text-white hover:text-white hover:bg-gray-700'
                  }`}
                >
                  Room Design
                </Link> */}
                <Link 
                  to="/about" 
                  className={`px-3 py-2 rounded-md text-sm font-medium ${
                    isActive('/about') 
                      ? 'bg-gray-800 text-white' 
                      : 'text-white hover:text-white hover:bg-gray-700'
                  }`}
                >
                  About
                </Link>
                <Link 
                  to="/contact" 
                  className={`px-3 py-2 rounded-md text-sm font-medium ${
                    isActive('/contact') 
                      ? 'bg-gray-800 text-white' 
                      : 'text-white hover:text-white hover:bg-gray-700'
                  }`}
                >
                  Contact
                </Link>
              </div>

              {/* Buttons */}
              <div className="flex items-center space-x-4">
                <Link
                  to="/room-design"
                  className="px-4 py-2 rounded-md text-sm font-medium bg-blue-600 text-white hover:bg-blue-700"
                >
                  Get Started
                </Link>
                
                {isAuthenticated ? (
                  <div 
                     className="relative"
                     onMouseEnter={() => setIsUserMenuOpen(true)}
                     onMouseLeave={() => setIsUserMenuOpen(false)}
                   >
                    <div className="flex items-center space-x-2 px-3 py-2 rounded-md text-sm font-medium text-gray-300 hover:text-white hover:bg-gray-700 cursor-pointer user-menu-container">
                      {/* 用户头像 */}
                      {user?.picture ? (
                        <img
                          src={user.picture}
                          alt="User Avatar"
                          className="w-8 h-8 rounded-full object-cover"
                        />
                      ) : (
                        <div className="w-8 h-8 rounded-full bg-blue-500 flex items-center justify-center text-white">
                          {getUserAvatarLetter()}
                        </div>
                      )}
                      <span className="hidden md:inline">{getUserDisplayName()}</span>
                    </div>
                    
                    {isUserMenuOpen && (
                      <div 
                        className="absolute right-0 z-[999] user-menu-container"
                        onMouseEnter={() => setIsUserMenuOpen(true)}
                        onMouseLeave={() => setIsUserMenuOpen(false)}
                      >
                        <UserDropdown />
                      </div>
                    )}
                  </div>
                ) : (
                  <Link
                    to="/login"
                    className="px-4 py-2 rounded-md text-sm font-medium text-gray-300 hover:text-white hover:bg-gray-700"
                  >
                    Login
                  </Link>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Mobile drawer menu */}
        <div className={`fixed inset-0 z-50 md:hidden transition-opacity duration-300 ${isMobileMenuOpen ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}>
          {/* Backdrop */}
          <div 
            className={`fixed inset-0 bg-black transition-opacity duration-300 ${isMobileMenuOpen ? 'opacity-50' : 'opacity-0'}`}
            onClick={() => setIsMobileMenuOpen(false)}
          ></div>
          
          {/* Drawer */}
          <div className={`fixed top-0 left-0 h-full w-80 bg-gray-900 shadow-xl transform transition-transform duration-300 ease-in-out ${isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full'}`}>
            {/* Drawer header */}
            <div className="flex items-center justify-between p-4 border-b border-gray-700">
              <Link to="/" className="text-xl font-bold text-white" onClick={() => setIsMobileMenuOpen(false)}>
                RoomGPT
              </Link>
              <button
                onClick={() => setIsMobileMenuOpen(false)}
                className="p-2 rounded-md text-gray-400 hover:text-white hover:bg-gray-700"
              >
                <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            
            {/* Drawer content */}
            <div className="px-4 pt-4 pb-3 space-y-1">
              <Link
                to="/"
                className={`block px-3 py-2 rounded-md text-base font-medium ${
                  isActive('/')
                    ? 'bg-gray-800 text-white'
                    : 'text-gray-300 hover:text-white hover:bg-gray-700'
                }`}
                onClick={() => setIsMobileMenuOpen(false)}
              >
                Home
              </Link>
              <Link
                to="/styles"
                className={`block px-3 py-2 rounded-md text-base font-medium ${
                  isActive('/styles')
                    ? 'bg-gray-800 text-white'
                    : 'text-gray-300 hover:text-white hover:bg-gray-700'
                }`}
                onClick={() => setIsMobileMenuOpen(false)}
              >
                Styles
              </Link>
              <Link
                to="/gallery"
                className={`block px-3 py-2 rounded-md text-base font-medium ${
                  isActive('/gallery')
                    ? 'bg-gray-800 text-white'
                    : 'text-gray-300 hover:text-white hover:bg-gray-700'
                }`}
                onClick={() => setIsMobileMenuOpen(false)}
              >
                Gallery
              </Link>
              <Link
                to="/room-design"
                className={`block px-3 py-2 rounded-md text-base font-medium ${
                  isActive('/room-design')
                    ? 'bg-gray-800 text-white'
                    : 'text-gray-300 hover:text-white hover:bg-gray-700'
                }`}
                onClick={() => setIsMobileMenuOpen(false)}
              >
                Room Design
              </Link>
              <Link
                to="/about"
                className={`block px-3 py-2 rounded-md text-base font-medium ${
                  isActive('/about')
                    ? 'bg-gray-800 text-white'
                    : 'text-gray-300 hover:text-white hover:bg-gray-700'
                }`}
                onClick={() => setIsMobileMenuOpen(false)}
              >
                About
              </Link>
              <Link
                to="/contact"
                className={`block px-3 py-2 rounded-md text-base font-medium ${
                  isActive('/contact')
                    ? 'bg-gray-800 text-white'
                    : 'text-gray-300 hover:text-white hover:bg-gray-700'
                }`}
                onClick={() => setIsMobileMenuOpen(false)}
              >
                Contact
              </Link>
              <Link
                to="/room-design"
                className="block px-3 py-2 rounded-md text-base font-medium bg-blue-600 text-white hover:bg-blue-700"
                onClick={() => setIsMobileMenuOpen(false)}
              >
                Get Started
              </Link>
            </div>
          </div>
        </div>
      </div>
    </nav>
  );
};

export default Navbar;

/* 在组件文件中添加全局样式 */
const style = document.createElement('style');
style.innerHTML = `
@keyframes spin-slow {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
.animate-spin-slow {
  animation: spin-slow 4s linear infinite;
}
`;
document.head.appendChild(style);


















